<template>
  <div class="home">
    <div class="banner">
      <div class="banner-content">
        <h1>技术博客</h1>
        <p>分享编程知识和经验，让技术学习更简单</p>
      </div>
    </div>
    
    <div class="container">
      <div class="content-wrap">
        <div class="article-list" v-loading="loading">
          <article-card 
            v-for="article in articleList" 
            :key="article.id" 
            :article="article" 
          />
          
          <div class="empty-placeholder" v-if="!loading && articleList.length === 0">
            <el-empty description="暂无文章" />
          </div>
        </div>
        
        <div class="sidebar">
          <div class="sidebar-card hot-tags">
            <h3 class="sidebar-title">热门标签</h3>
            <div class="tag-cloud">
              <el-tag 
                v-for="tag in hotTags" 
                :key="tag" 
                effect="plain" 
                @click="handleTagClick(tag)"
                class="tag-item"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          
          <div class="sidebar-card hot-articles">
            <h3 class="sidebar-title">热门文章</h3>
            <ul class="hot-article-list">
              <li v-for="(article, index) in hotArticles" :key="article.id" @click="navigateToDetail(article.id)">
                <span class="rank-num" :class="{'top-rank': index < 3}">{{ index + 1 }}</span>
                <span class="article-title">{{ article.title }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      
      <div class="pagination-container" v-if="articleList.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import ArticleCard from '../components/ArticleCard.vue'
import { useRouter } from 'vue-router'
import { useArticleStore } from '../store/article'
import { getArticleList } from '../api/article'

const router = useRouter()
const articleStore = useArticleStore()

// 文章列表
const articleList = computed(() => articleStore.articleList)
const loading = computed(() => articleStore.loading)
const total = computed(() => articleStore.total)
const currentPage = computed({
  get: () => articleStore.currentPage,
  set: (val) => articleStore.currentPage = val
})
const pageSize = computed({
  get: () => articleStore.pageSize,
  set: (val) => articleStore.pageSize = val
})

// 热门标签（示例数据）
const hotTags = ref([
  'Vue', 'React', 'JavaScript', 'TypeScript', 'Node.js',
  'CSS', 'HTML', 'Webpack', 'Vite', 'Docker'
])

// 热门文章（示例数据）
const hotArticles = ref([
  { id: '1', title: 'Vue3 组合式 API 详解' },
  { id: '2', title: 'TypeScript 高级类型与类型体操' },
  { id: '3', title: 'React Hooks 最佳实践' },
  { id: '4', title: 'Vite 构建工具全面解析' },
  { id: '5', title: 'Node.js 性能优化技巧' }
])

// 获取文章列表
async function fetchArticles() {
  try {
    articleStore.setLoading(true)
    
    // 实际项目中应该调用API获取文章
    // 这里使用模拟数据
    // const res = await getArticleList({
    //   page: currentPage.value,
    //   limit: pageSize.value
    // })
    
    // 模拟数据
    const mockArticles = Array(10).fill(0).map((_, index) => ({
      id: String(index + 1),
      title: `文章标题 ${index + 1}`,
      content: `这是文章内容的摘要，一般会显示文章开头的一部分内容。这是第 ${index + 1} 篇示例文章...`,
      author: '作者名称',
      authorId: 'user1',
      authorAvatar: '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      tags: (() => {
        const allTags = ['Vue', 'React', 'JavaScript', 'TypeScript', 'Node.js', 'CSS', 'HTML', 'Webpack', 'Vite']
        // 随机选择2-4个标签
        return allTags.sort(() => Math.random() - 0.5).slice(0, Math.floor(Math.random() * 3) + 2)
      })(),
      coverImage: index % 3 === 0 ? `https://picsum.photos/id/${(index * 10) + 10}/800/400` : ''
    }))
    
    articleStore.setArticleList(mockArticles)
    articleStore.setPagination({
      total: 100,
      currentPage: currentPage.value,
      pageSize: pageSize.value
    })
  } catch (error) {
    console.error('获取文章列表失败:', error)
  } finally {
    articleStore.setLoading(false)
  }
}

// 处理页码变化
function handleCurrentChange(page: number) {
  fetchArticles()
}

// 处理每页条数变化
function handleSizeChange(size: number) {
  fetchArticles()
}

// 处理标签点击
function handleTagClick(tag: string) {
  // 实现标签过滤逻辑
  console.log('标签点击:', tag)
  // 可以根据标签筛选文章
  fetchArticles()
}

// 跳转到文章详情
function navigateToDetail(id: string) {
  router.push(`/article/${id}`)
}

onMounted(() => {
  fetchArticles()
})
</script>

<style scoped lang="scss">
.home {
  padding-top: 60px; // 为固定的header留出空间
}

.banner {
  height: 400px;
  background: linear-gradient(135deg, #2979ff 0%, #1e88e5 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-bottom: 30px;
  
  .banner-content {
    text-align: center;
    max-width: 800px;
    padding: 0 20px;
    
    h1 {
      font-size: 48px;
      margin-bottom: 20px;
    }
    
    p {
      font-size: 20px;
      opacity: 0.9;
    }
  }
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.content-wrap {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
}

.article-list {
  flex: 1;
  min-height: 500px;
}

.sidebar {
  width: 300px;
  
  @media (max-width: 768px) {
    display: none;
  }
}

.sidebar-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.sidebar-title {
  font-size: 18px;
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  color: #303133;
}

.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  
  .tag-item {
    cursor: pointer;
  }
}

.hot-article-list {
  list-style: none;
  padding: 0;
  margin: 0;
  
  li {
    display: flex;
    align-items: flex-start;
    padding: 10px 0;
    cursor: pointer;
    transition: color 0.2s;
    
    &:hover {
      .article-title {
        color: #409eff;
      }
    }
    
    &:not(:last-child) {
      border-bottom: 1px dashed #f0f0f0;
    }
  }
  
  .rank-num {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 4px;
    background-color: #f0f0f0;
    color: #606266;
    font-size: 14px;
    margin-right: 10px;
    flex-shrink: 0;
    
    &.top-rank {
      background-color: #409eff;
      color: white;
    }
  }
  
  .article-title {
    flex: 1;
    font-size: 14px;
    line-height: 1.6;
    color: #606266;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  margin-bottom: 50px;
}

.empty-placeholder {
  margin-top: 50px;
}
</style> 